package com.azt.front.interceptor;

import com.azt.api.enums.RoleTypeEnum;
import com.azt.api.pojo.Company;
import com.azt.api.pojo.Role;
import com.azt.front.permission.ClearRequire;
import com.azt.front.permission.RequirePurchase;
import com.azt.front.utils.ContextUtil;
import com.azt.utils.CommonUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 仅供应商可访问
 * Created by 张栋 on 2016/12/5 13:32
 */
public class RequirePurchaseInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RequirePurchase requirePurchase = handlerMethod.getMethodAnnotation(RequirePurchase.class);
            ClearRequire clearRequire = handlerMethod.getMethodAnnotation(ClearRequire.class);
            if(clearRequire == null && requirePurchase == null) {
                requirePurchase = handlerMethod.getBean().getClass().getAnnotation(RequirePurchase.class);
            }

            if(requirePurchase != null) {
                Company company = ContextUtil.getCompany();
                if(company==null){
                    CommonUtil.redirectToLogin(request,response);
                    return  false;
                }
                Integer currentRoleType = ContextUtil.getCurrentRoleType();
                if(currentRoleType!= RoleTypeEnum.PURCHASER.getValue()){//当前不是采购商
                    /**
                     * 孙俊,点对应的连接,切换到对应的身份
                     * Created by 张栋 on 2017/3/22 19:04
                     */
                    Role purhcaseRole = ContextUtil.hasPurchaser();
                    if(purhcaseRole!=null){
                        ContextUtil.setCurrentRole(purhcaseRole);
                    }else{
                        response.sendRedirect("/user/userCenter");
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
